前一天介紹了中央控管計時器的方式,今天接續把這個方法用在動畫當中。另外進一步在測試中使用此控管的方法。而下一章會有更進階跟複雜的進行程式碼計值(code evaluation)。
var timers = {
timerID: 0,
timers: [],
add: function(fn){
this.timers.push(fn)
},
start: function() {
if (this.timerId) return;
(function runNext() {
if (timers.timers.length > 0) {
for (var i = 0; i < timers.timers.length; i++) {
if(timers.timers[i]() === false) {
timers.timers.splice(i,1);
i--;
}
}
timers.timerID = setTimeout(runNext, 0);
}
})()
},
stop: function() {
clearTimeout(this.timerID);
this.timerID = 0;
}
}
var box = document.getElementById("
box"), x = 0, y = 20;
timers.add(function() {
box,style.left = x + "px";
if (++x > 50) return false;
});
timers.add(function() {
box,style.top = y + "px";
y + = 2;
if (y > 120) return false;
});
//timers.timers
[fn , fn]
timers.timers.pop()
[fn , fn]
timers.start()
(function(){
var queue = [],paused = false; //狀態保留
this.test = function(fn) { //定義韓式能註冊受測函式
queue.push(fn);
runTest();
};
this.pause = function() { //定義函式能暫停測試
paused = true;
};
this.resume = function() { //定義函式能恢復測試
paused = false;
setTimeout(runTest, 1);
};
function runTest() { //執行測試
if(!paused && queue.length){
queue.shift()();
if (!paused) resume();
}
}
})()
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing